import { defineStore } from 'pinia'
import { ref, watch, onMounted } from 'vue'

// --- 把所有有效的主题名定义为一个常量数组 ---
const VALID_THEMES = ['light', 'dark', 'sepia', 'azure'];
const DEFAULT_THEME = 'light'; // 定义默认主题

export const useThemeStore = defineStore('theme', () => {
    // 1. 定义主题状态，尝试从 localStorage 读取，默认为 'light'
    // 1. 读取 localStorage 时，检查值是否有效，无效则使用默认值
    const getInitialTheme = () => {
        const storedTheme = localStorage.getItem('theme');
        return VALID_THEMES.includes(storedTheme) ? storedTheme : DEFAULT_THEME;
    };
    const currentTheme = ref(getInitialTheme());
    
    
    
    // 2. 定义切换主题的 action
    function setTheme(themeName) {
        if (VALID_THEMES.includes(themeName)) { // 限制可选主题
            currentTheme.value = themeName;
        } else {
            console.warn(`Invalid theme name: ${themeName}. Defaulting to 'light'.`);
            currentTheme.value = DEFAULT_THEME;
        }
    }
    
    // 3. watch 监听器需要移除所有可能的主题类，再添加新的
    watch(currentTheme, (newTheme, oldTheme) => {
        localStorage.setItem('theme', newTheme);
        
        // --- 关键修改：确保移除所有已知的主题类 ---
        // 使用扩展运算符 (...) 将 VALID_THEMES 数组展开作为参数
        document.documentElement.classList.remove(...VALID_THEMES);
        
        // 添加新的主题类
        document.documentElement.classList.add(newTheme);
        console.log(`Theme changed to: ${newTheme}`);
    }, { immediate: false }); // 保持 immediate: false
    
    
    // 4. 组件挂载时应用初始主题 (确保 CSS 加载后应用 class)
    onMounted(() => {
        const initialTheme = currentTheme.value; // 已经包含了有效性检查
        // --- 关键修改：确保移除所有可能的主题类 ---
        document.documentElement.classList.remove(...VALID_THEMES.filter(t => t !== initialTheme)); // 移除除了初始主题外的所有类
        
        if (!document.documentElement.classList.contains(initialTheme)) {
            document.documentElement.classList.add(initialTheme);
            console.log(`Applied initial theme on mount: ${initialTheme}`);
        } else {
            console.log(`Initial theme already applied: ${initialTheme}`);
        }
    });
    
    
    // 5. 返回状态和 action
    return {
        currentTheme,
        setTheme
    }
})